const Neo4j = require('node-neo4j')

// 查询节点详情
const getNodeInfo = ({ url }, nodeId) => {
  return new Promise(resolve => {
    const neo = new Neo4j(url)
    const cql = `MATCH (N) WHERE ID(N)=${nodeId} RETURN N, LABELS(N)`
    neo.cypherQuery(cql, (err, res) => {
      if (err) throw err
      resolve({
        ...res.data[0][0],
        type: res.data[0][1]
      })
    })
  })
}

// 查询关系详情
const getRelaInfo = ({ url }, rid) => {
  return new Promise(resolve => {
    const neo = new Neo4j(url)
    const cql = `MATCH ()-[R]-() WHERE ID(R)=${rid} RETURN R, TYPE(R)`
    neo.cypherQuery(cql, (err, res) => {
      if (err) throw err
      resolve({
        ...res.data[0][0],
        name: res.data[0][1],
      })
    })
  })
}

// 查询图谱数据
const select = ({ url }, keywords, level, limit) => {
  return new Promise(resolve => {
    const cqlMap = {
      '1': `MATCH P=(N) WHERE N.name =~ ".*${keywords}.*" RETURN P LIMIT ${limit}`,
      '2': `MATCH P=(N)-[]-() WHERE N.name =~ ".*${keywords}.*" RETURN P LIMIT ${limit}`,
      '3': `MATCH P=(N)-[]-()-[]-() WHERE N.name =~ ".*${keywords}.*" RETURN P LIMIT ${limit}`
    }
    const neo = new Neo4j(url)
    const cql = cqlMap[level]
    neo.cypherQuery(cql, (err, res) => {
      if (err) throw err
      // console.log(res)
      resolve(res.data)
    })
  })
}

module.exports = {
  select,
  getNodeInfo,
  getRelaInfo
}